import React, { Component } from 'react';
import {
    StyleSheet,
    Text,
    View,
    TouchableOpacity,
    Image,
    FlatList,
    StatusBar,
    TextInput,
    ScrollView,
    ActivityIndicator, WebView, DeviceEventEmitter
} from 'react-native';
import { base } from "../../../../assets/style";
import LinearGradient from "react-native-linear-gradient";
import CheckBox from "react-native-check-box";
import Confirm from "../../../../components/confirm/Confirm";
import Toast from "react-native-easy-toast";
import { API } from "../../../../api";
import { getUserInfoStorage } from "../../../../utils/login";
import { i18n } from "../../../../utils/locales/i18n";
import {geetestURL_8080} from "../../../../config";

type Props = {};
export default class MyAssets extends Component<Props> {
    static navigationOptions = ({ navigation }) => {
        return {
            title: 'FCC' + i18n.t('withdraw'),
            headerStyle: {
            },
            headerTintColor: '#0f0f0f',
            headerBackTitle: null
        }
    };
    constructor() {
        super();
        this.state = {
            wdAmount: '',
            remark: '',
            address: '',
            messageCode: '',
            emailCode: '',
            WithdrawLimitAndFee: '',
            isChecked: true,
            loading: true,
            second: 60,
            isSend: false,
            userData: ''
                // AreCode: "86"
                // AssPass: false
                // BankInfo: [{…}]
                // Email: "915518319@qq.com"
                // GoogleAuth: "FMBCAIIEDX6VPA6D"
                // GoogleOpen: 1
                // HadAd: 2
                // Kyc: 2
                // Name: "E231e"
                // Phone: "15622321273"
                // TxFail: 15
                // TxSuc: 11
                // Username: "dewdew"
        }
    }
    componentWillMount(): void {
        this._initData()
        DeviceEventEmitter.addListener('refresh_wd_address', () => {
            this._initData()
        })
    }
    // 提交提币
    submitWithdraw = async () => {
        if (!this.state.messageCode || !this.state.wdAmount || !this.state.isChecked) {
            this.refs.toast.show(i18n.t('plz_cpl'))
            return
        }
        if (Number(this.state.wdAmount) < Number(this.state.WithdrawLimitAndFee.Mix) || Number(this.state.wdAmount) > Number(this.state.WithdrawLimitAndFee.Max)) {
            this.refs.toast.show(i18n.t('overflow'))
            return
        }
        const reqData = {
            captcha: this.state.messageCode,
            key: this.state.userData.Phone ? this.state.userData.Phone : this.state.userData.Email,
            withdrawRemark: this.state.remark || ' ',
            withdrawSum: this.state.wdAmount + '',
            withdrawToken: "fcc"
        }
        const res = await API._fetch('submitWithdrawOrder', reqData)
        if (res && res.code === 10000) {
            this.toWithdrawSuccess(res.data)
        } else {
            this.refs.toast.show(res.msg || i18n.t('o_defeat'))
        }
    }

    // 获取验证码
    getVerifyCode = () => {
        this.setState({
            geetestVisible: true
        })
    }
    // webview加载失败处理
    onGeetestError = () => {
        this.setState({
            geetestVisible: false
        })
        alert('Geetest faild!')
    }
    // 处理极验返回的消息
    handleGeetestMessage = (e) => {
        e.persist();
        if (e.nativeEvent.data === 'send') {
            // 成功发送，隐藏webview
            setTimeout(() => {
                this.setState({
                    geetestVisible: false,
                    isSend: true
                })
                // 重新发送倒计时
                const timer = setInterval(() => {
                    this.setState({
                        second: this.state.second - 1
                    })
                    if (this.state.second <= 0) {
                        clearInterval(timer)
                        this.setState({
                            second: 60,
                            isSend: false
                        })
                    }
                }, 1000)
            }, 0)
        }
    }
    // 向极验webview 发送数据
    sendMessageToGeetest = () => {
        // type: 1注册 2绑定 3设置 4重置登陆密码 5重置资金密码 6提币验证码
        let options;
        if (this.state.userData.Phone) {
            // 手机
            options = {
                to: '+' + this.state.userData.AreCode + this.state.userData.Phone,
                type: 6
            }
        } else {
            // 邮箱
            options = {
                to: this.state.userData.Email,
                type: 6
            }
        }
        this.refs.webview.postMessage(JSON.stringify(options))
    }
    _initData = async () => {
        // 获取初始数据
        const [res1, res2, res3] = await Promise.all([
            API._fetch('getWithdrawLimitAndFee', { token: 'fcc' }),
            API._fetch('getWithdrawAddress', { token: 'fcc' }),
            getUserInfoStorage()
        ])
        // code: 10000
        // data: {Fee: 10, Max: 10000, Min: 10}
        // Fee: 10
        // Max: 10000
        // Min: 10
        // msg: "获取提币限额和手续费成功"
        // status: 200

        if (res1.code === 10000 && res2.code === 10000) {
            this.setState({
                WithdrawLimitAndFee: res1.data,
                address: res2.data.Address,
                userData: res3
            })
        }
        this.setState({
            loading: false
        })
    }
    toWithdrawSuccess = (params) => {
        this.props.navigation.navigate('WithdrawSuccess', { detail: JSON.stringify(params) })
    }
    render() {
        return (
            <View style={{ width: '100%', height: '100%' }}>
                {/*极验验证 */}
                { this.state.geetestVisible ? (
                    <View style={{ position: 'absolute', top: 0, left: 0, width: '100%', height: '100%', zIndex: 999 }}>
                        <WebView
                            ref={'webview'}
                            onMessage={ msg => this.handleGeetestMessage(msg)}
                            onLoad={this.sendMessageToGeetest}
                            bounces={false}
                            javaScriptEnabled={true}
                            onError={this.onGeetestError}
                            style={{ flex: 1 }}
                            // source={require('../../../../pages/geetest_8080.html')}
                            source={{uri: geetestURL_8080}}
                        />
                    </View>
                ) : null}
                {/*更新充币地址*/}
                <Confirm
                    title={i18n.t('info')}
                    negative={i18n.t('cancel')}
                    positive={i18n.t('confirm')}
                    modalVisible={false}
                    handleCancelOrder={() => this.setState({ updateConfirm: false })}
                    handleConfirmOrder={this.updateAddress}
                >
                    <View style={[base.flex_1, base.flex_col_center]}>
                        <Text>{ i18n.t('info7') }</Text>
                    </View>
                </Confirm>
                {/*toast*/}
                <Toast ref="toast" position='bottom' positionValue={200}/>
                { this.state.loading ? (
                    <View style={[base.flex_1, base.flex_col_center, base.bg_white]}>
                        <ActivityIndicator size="large" color="#ff7606" />
                        <View style={{paddingTop: 15}}>
                            <Text style={[base.color_orange]}>{ i18n.t('loading') }</Text>
                        </View>
                    </View>
                ) : (
                    <View style={[base.flex_1, base.content_container, { backgroundColor: '#eee', paddingVertical: 10 }]}>

                        <View style={[{ backgroundColor: '#fff', borderRadius: 5, padding: 15 }]}>
                            <View style={{paddingBottom: 20, borderBottomColor: '#eee', borderBottomWidth: 1}}>
                                <Text style={[base.color_gray]}>
                                    { i18n.t('info8') } { this.state.WithdrawLimitAndFee.Fee } FCC. { i18n.t('info9') }：{ this.state.WithdrawLimitAndFee.Min } FCC, { i18n.t('info10') }：{ this.state.WithdrawLimitAndFee.Max } FCC</Text>
                            </View>
                            <View style={{paddingTop: 10}}>
                                <View style={{ height: 40, width: '100%', borderColor: '#d2d2d2', borderWidth: 0.5, borderRadius: 5, marginVertical: 5 }}>
                                    <TextInput
                                        style={{height: '100%', flex: 1, paddingLeft: 10}}
                                        onChangeText={(text) => this.setState({wdAmount: text})}
                                        placeholder={i18n.t('info11')}
                                        value={this.state.wdAmount}
                                        keyboardType={'numeric'}
                                    />
                                </View>
                                <View style={{ height: 40, width: '100%', borderColor: '#d2d2d2', borderWidth: 0.5, borderRadius: 5, marginVertical: 5 }}>
                                    <TextInput
                                        style={{height: '100%', flex: 1, paddingLeft: 10}}
                                        onChangeText={(text) => this.setState({remark: text})}
                                        placeholder={i18n.t('info12')}
                                        value={this.state.remark}
                                    />
                                </View>
                                <View style={{ width: '100%', marginVertical: 10 }}>
                                    {/*an address*/}
                                    <View style={[base.flex_row_center, { borderBottomColor: '#eee', borderBottomWidth: 0 }]}>
                                        <View style={[base.flex_1, { padding: 0 }]}>
                                            {/*<Text numberOfLines={2} ellipsizeMode={'middle'} style={[base.color_gray]}>*/}
                                                {/*{ this.state.address ? this.state.address : '请添加地址' }*/}
                                            {/*</Text>*/}

                                            <TextInput
                                                underlineColorAndroid="transparent"
                                                style={{borderColor: '#e5e5e5', width: '100%', backgroundColor: '#eee', borderWidth: 0.5, borderRadius: 3, paddingHorizontal: 15, paddingVertical: 20}}
                                                placeholder={i18n.t('remark')}
                                                onChangeText={(text) => this.setState({remark: text})}
                                                value={this.state.address}
                                                multiline={true}
                                                editable={false}
                                            />
                                        </View>
                                    </View>
                                    <View style={[base.flex_row_start, { height: 30}]}>
                                        <TouchableOpacity style={[base.flex_row_start]} onPress={() => this.props.navigation.navigate('AddWDAddress')}>
                                            <Image style={{width: 12, height: 12}} source={require('../../../../images/mine/edit-1.png')}/>
                                            <View style={{paddingLeft: 5}}><Text style={base.color_gray}>{ i18n.t('e_addr') }</Text></View>
                                        </TouchableOpacity>
                                    </View>
                                </View>
                                { this.state.userData.Phone ? (
                                    <View style={{ height: 40, width: '100%', borderColor: '#d2d2d2', borderWidth: 0.5, borderRadius: 5, marginVertical: 5, flexDirection: 'row' }}>
                                        <TextInput
                                            style={{height: '100%', flex: 1, paddingLeft: 10, borderRightColor: '#d2d2d2', borderRightWidth: 1}}
                                            onChangeText={(text) => this.setState({messageCode: text})}
                                            placeholder={i18n.t('c_message')}
                                            value={this.state.messageCode}
                                        />
                                        { !this.state.isSend ? (
                                            <TouchableOpacity style={{width: 100, height: '100%'}} onPress={this.getVerifyCode}>
                                                <View style={[base.flex_1, base.flex_row_center]}>
                                                    <Text style={[base.color_orange, {fontSize: 16}]}>{ i18n.t('cag') }</Text>
                                                </View>
                                            </TouchableOpacity>
                                        ) : (
                                            <TouchableOpacity style={{width: 100, height: '100%'}}>
                                                <View style={[base.flex_1, base.flex_row_center]}>
                                                    <Text style={[base.color_gray, {fontSize: 12}]}>{this.state.second} s</Text>
                                                </View>
                                            </TouchableOpacity>
                                        ) }
                                    </View>
                                ) : (
                                    <View style={{ height: 40, width: '100%', borderColor: '#d2d2d2', borderWidth: 0.5, borderRadius: 5, marginVertical: 5, flexDirection: 'row' }}>
                                        <TextInput
                                            style={{height: '100%', flex: 1, paddingLeft: 10, borderRightColor: '#d2d2d2', borderRightWidth: 1}}
                                            onChangeText={(text) => this.setState({emailCode: text})}
                                            placeholder={i18n.t('m_message')}
                                            value={this.state.emailCode}
                                        />
                                        <TouchableOpacity style={{width: 100, height: '100%'}}>
                                            <View style={[base.flex_1, base.flex_row_center]}><Text style={[base.color_orange, {fontSize: 16}]}>点击获取</Text></View>
                                        </TouchableOpacity>
                                    </View>) }
                                <View style={{ paddingVertical: 15, height: 80 }}>
                                    <CheckBox
                                        style={{flex: 1}}
                                        onClick={() => {
                                            this.setState({
                                                isChecked: !this.state.isChecked
                                            })
                                        }}
                                        rightText={i18n.t('info13')}
                                        isChecked={this.state.isChecked}
                                        rightTextStyle={{color: '#808080'}}
                                        checkBoxColor={'#ff7606'}
                                    />
                                </View>
                            </View>
                        </View>
                        <View style={[base.flex_1, base.flex_col_center, { paddingVertical: 20, paddingBottom: 10 }]}>
                            <TouchableOpacity style={{width: '80%'}} onPress={this.submitWithdraw}>
                                <LinearGradient
                                    start={{x: 0, y: 0}}
                                    end={{x: 1, y: 1}}
                                    colors={['#feac1c', '#ff7506']}
                                    style={{ width: '100%', height: 46, borderRadius: 23, justifyContent: 'center', alignItems: 'center' }}
                                >
                                    <Text style={{color: '#fff', fontSize: 16}}>{ i18n.t('submit') }</Text>
                                </LinearGradient>
                            </TouchableOpacity>
                            <TouchableOpacity onPress={() => this.props.navigation.goBack()} style={{width: '80%', marginTop: 20}}>
                                <View
                                    style={{ width: '100%', height: 46, borderRadius: 23, borderWidth: 0.5, borderColor: '#b3b3b3', justifyContent: 'center', alignItems: 'center' }}
                                >
                                    <Text style={{color: '#808080', fontSize: 16}}>{ i18n.t('cancel') }</Text>
                                </View>
                            </TouchableOpacity>
                        </View>
                    </View>
                ) }
            </View>
        )
    }
}

const styles = StyleSheet.create({
});
